# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals

# 管理后台的菜单
ADMIN_MENU_ORDER = (
    ("网站内容",
     ("article.ArticlePost", "article.ArticleCategory", "generic.Keyword",
      "generic.AssignedKeyword", "generic.ThreadedComment", "wlcore.Region",)),
    ("用户中心",
     ("auth.User", ("用户组", "auth.Group"),)),
    ("微信引擎",
     ("wechat.WechatPannel", "wechat.WechatMenu", "wechat.WechatAutoreply",
      "wechat.WechatSucaiSingle", "wechat.WechatSucaiMulti", "wechat.WechatFans", "wechat.WechatSetting",)),
    ("网站管理",
     ("wlcore.SiteSetting", "conf.Setting", "wlcore.DevSetting", ("媒体库", "fb_browse"), "admin.LogEntry",)),
)

DASHBOARD_TAGS = (
    ("wenlincms_tags.app_list",),
    ("comment_tags.recent_comments",),
    ("wenlincms_tags.recent_actions",),
    ("wlcore_tags.recent_index_head",),
    ("wlcore_tags.sys_info",),
)

# 识别手机端的UA
DEVICE_USER_AGENTS = (
    ('mobile', (
        '2.0 MMP', '2\.0\ mmp', '240x320', '320x320', '176x220''400X240', 'acer\ s100',
        'AvantGo', 'Android', 'android', 'alcatel', 'amoi', 'amoi', 'archos5', 'asus', 'au\-mic', 'audiovox', 'avantgo',
        'BlackBerry', 'BlackBerry9530', 'blackberry', 'Blazer', 'blazer', 'bunjalloo', 'bird', 'benq', 'blackberry',
        'blackberry9500', 'blackberry9530', 'blackberry9550', 'blackberry\ 9800',
        'Cellphone', 'cldc', 'coolpad', 'cdm', 'cellphone', 'cupcake',
        'Danger', 'DoCoMo', 'dopod', 'docomo', 'danger', 'ddipocket', 'docomo\ ht\-03a', 'dream',
        'Elaine/3.0', 'EudoraWeb', 'ericsson', 'elaine/3\.0', 'eudoraweb', 'Googlebot-Mobile', 'gionee',
        'hiptop', 'helio', 'hosin', 'huawei', 'haier', 'hp\.ipaq', 'htc', 'htc\ hero', 'htc\ magic', 'htc_dream',
        'htc_magic', 'liquid\ build', 'foma', 'fly',
        'IEMobile', 'iPhone', 'iPod', 'iPad', 'iemobile', 'i\-mobile', 'incognito', 'ipad', 'iphone', 'ipod',
        'java', 'jig browser', 'j\-phone', 'NetFront', 'netfront', 'novarra',
        'KYOCERA/WX310K', 'ktouch', 'kddi', 'kindle', 'konka', 'kwc', 'kyocera/wx310k',
        'LG/U990', 'LG-TU915 Obigo', 'LGE VX', 'longcos', 'lenovo', 'lg', 'lg/u990', 'lg\-gw620', 'lge\ vx',
        'MIDP-2.', 'MMEF20', 'MOT-V', 'mobile', 'meizu', 'motorola', 'maui',
        'maemo', 'midp', 'midp\-2\.0', 'mmef20', 'mmp', 'mobilephone', 'mot\-mb200', 'mot\-mb300', 'mot\-v',
        'Newt', 'Nintendo Wii', 'Nitro', 'Nokia', 'Nokia5800', 'nokia', 'nexian',
        'newgen', 'newt', 'nexus\ one', 'nintendo\ ds', 'nintendo\ wii', 'nitro',
        'Opera Mini', 'opera mobi', 'opera mini', 'o2', 'openweb', 'opera\ mini', 'opera\ mobi', 'opera\.mobi',
        'Palm', 'PlayStation Portable', 'portalmmm', 'series', 'smartphone', 'spice',
        'Proxinet', 'palmsource', 'pieplus', 'philips', 'pantech', 'ProxiNet', 'psp',
        'palm', 'panasonic', 'pantech', 'pdxgw', 'pg', 'phone', 'playstation\ portable', 'portalmmm', 'proxinet',
        'SHARP-TQ-GX10', 'SHG-i900', 'Small', 'SonyEricsson', 'sony', 'Symbian OS', 'SymbianOS', 'symbian',
        'sagem', 'samsung', 'samsung\-s8000', 'sanyo', 'sch', 'sec', 'sendo', 'series60.*webkit', 'series60/5\.0',
        'sharp', 'sharp\-tq\-gx10', 'small', 'smartphone', 'softbank', 'sonyericsson', 'sonyericssone10',
        'sonyericssonu20', 'sonyericssonx10', 'sph', 'symbian\ os', 'symbianos',
        'TS21i-10', 'techfaith', 't\-mobile\ mytouch\ 3g', 't\-mobile\ opal', 'tattoo', 'toshiba', 'treo', 'ts21i\-10',
        'UP.Browser', 'UP.Link', 'ucweb', 'up.browser', 'up.link',
        'up\.browser', 'up\.link', 'uts', 'sgh', 'qtek', 'vertu', 'vodafone',
        'webOS', 'webOS', 'webos', 'wap', 'Windows CE', 'windows ce', 'wellcom', 'WinWAP',
        'webmate', 'willcome', 'windows\ ce', 'windows\.ce', 'winwap',
        'xda', 'xda', 'YahooSeeker/M1A1-R2D2', 'zte-', 'zte', '^lct',)),
)

########################
# MAIN DJANGO SETTINGS #
########################

ADMINS = (('feichi', 'feichi@longfeichi.com'),)
MANAGERS = ADMINS

##################
# 域名和子站相关设置 #
##################

ALLOWED_HOSTS = ["wenlincms.com", ]

##################

TIME_ZONE = "Asia/Shanghai"
USE_TZ = True
DATETIME_FORMAT = 'Y-m-d H:i:s'
DATE_FORMAT = 'Y-m-d'
LANGUAGE_CODE = "zh-CN"

# Supported languages
_ = lambda s: s
LANGUAGES = (
    ('cn', _('Chinese')),
)

DEBUG = True

USE_I18N = False  # load the internationalization machinery.

# session 和 cookie 相关设置
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
SESSION_EXPIRE_AT_BROWSER_CLOSE = False
SESSION_COOKIE_AGE = 3600 * 12
# SESSION_COOKIE_DOMAIN = '.wenlincms.com'

# Tuple of IP addresses, as strings, that
INTERNAL_IPS = ("127.0.0.1",)

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    "django.template.loaders.filesystem.Loader",
    "django.template.loaders.app_directories.Loader",
)

AUTHENTICATION_BACKENDS = ("wenlincms.core.auth_backends.wenlincmsBackend",)

# The numeric mode to set newly-uploaded files to. The value should be
# a mode you'd pass directly to os.chmod.
FILE_UPLOAD_PERMISSIONS = 0o644
FILE_UPLOAD_MAX_MEMORY_SIZE = 8388608

import os, sys

PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1]

STATIC_URL = "/static/"

STATIC_ROOT = os.path.join(PROJECT_ROOT, "../static")

MEDIA_URL = "/media/"

MEDIA_ROOT = os.path.join(PROJECT_ROOT, "../media")

ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME

TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "../templates"),)

CACHE_ROOT = os.path.join(PROJECT_ROOT, "cache")

APP_ROOT = os.path.join(PROJECT_ROOT, "../wlapps")

sys.path.insert(0, APP_ROOT)  # 加入额外目录

################
# APPLICATIONS #
################

# 一些默认的框架的组件
INSTALLED_APPS = (
    "wenlincms.boot",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.staticfiles",
    "wenlincms.conf",
    "wenlincms.core",
    "wenlincms.generic",
)

try:
    from mainsys.local_config import APPS_CANNOT_INTSALL
except ImportError:
    APPS_CANNOT_INTSALL = ["utils", ]  # 禁止作为app安装的目录

# 根据wlapps里的目录进行动态设置
for ap in os.listdir(APP_ROOT):
    if ap not in APPS_CANNOT_INTSALL and os.path.isdir(os.path.join(APP_ROOT, ap)) and \
            os.path.exists(os.path.join(os.path.join(APP_ROOT, ap), "__init__.py")):
        INSTALLED_APPS += (ap,)

# List of processors used by RequestContext to populate the context.
# Each one should be a callable that takes the request object as its
# only parameter and returns a dictionary to add to the context.
TEMPLATE_CONTEXT_PROCESSORS = (
    "django.contrib.auth.context_processors.auth",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.debug",
    "django.core.context_processors.static",
    "django.core.context_processors.media",
    "django.core.context_processors.request",
    "django.core.context_processors.tz",
    "wenlincms.conf.context_processors.settings",
    "wlapps.wlcore.context_processors.sitesettings",
)

# List of middleware classes to use. Order is important; in the request phase,
# these middleware classes will be applied in the order given, and in the
# response phase the middleware will be applied in reverse order.
MIDDLEWARE_CLASSES = (
    "wenlincms.core.middleware.UpdateCacheMiddleware",
    "django.middleware.http.ConditionalGetMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "wenlincms.core.request.CurrentRequestMiddleware",
    "wenlincms.core.middleware.RedirectFallbackMiddleware",
    # "wenlincms.core.middleware.TemplateForHostMiddleware",
    "wlapps.wlcore.middleware.TemplateForThemeMiddleware",
    "wenlincms.core.middleware.TemplateForDeviceMiddleware",
    "wenlincms.core.middleware.AdminLoginInterfaceSelectorMiddleware",
    # Uncomment the following if using any of the SSL settings:
    # "wenlincms.core.middleware.SSLRedirectMiddleware",
    "wenlincms.core.middleware.FetchFromCacheMiddleware",
)

# Make these unique, and don't share it with anybody.
SECRET_KEY = "2b55264e-ccab-4258-8f1d-903760347665328f57b5-b9f3-4067-b17a-fa1d2b61296d39b338c8-d0f9-436a-b495-5ed76015f049"
NEVERCACHE_KEY = "8067f916-05f2-4d95-b63e-9ddfdca186e826e87476-dbff-41b9-8240-525a81268b1349adabf1-309a-4267-b033-e3fb78528d95"

# LOGGING SETTINGS
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {'format': '%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] '
                               '[%(module)s:%(funcName)s] [%(levelname)s]- %(message)s'},
        'simple': {'format': '%(asctime)s %(message)s'},
    },
    'filters': {
    },
    'handlers': {
        'error': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'mainsys/log/error.log',
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 100,
            'formatter': 'simple',
        },
        'search': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': 'mainsys/log/search.log',
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 100,
            'formatter': 'simple',
        }
    },
    'loggers': {
        'error': {
            'handlers': ['error'],
            'level': 'INFO',
            'propagate': False
        },
        'search': {
            'handlers': ['error'],
            'level': 'INFO',
            'propagate': False
        }
    }
}

#########################
# OPTIONAL APPLICATIONS #
#########################

# Store these package names here as they may change in the future since
# at the moment we are using custom forks of them.
PACKAGE_NAME_FILEBROWSER = "wlfilebrowser"
PACKAGE_NAME_ADMIN = "wladmin"

# These will be added to ``INSTALLED_APPS``, only if available.
OPTIONAL_APPS = (
    # "debug_toolbar",
    # "django_extensions",
    # "compressor",
    PACKAGE_NAME_FILEBROWSER,
    PACKAGE_NAME_ADMIN,
)

##################
# 缓存相关设置 #
##################

CACHE_MIDDLEWARE_SECONDS = 900
CACHE_MIDDLEWARE_KEY_PREFIX = 'wenlincms'
CACHE_MIDDLEWARE_ALIAS = 'default'

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',
        'LOCATION': CACHE_ROOT,
    }
}

###################################

##################
# 导入项目的本地设置
##################

try:
    from mainsys.local_config import *
except ImportError as e:
    if "local_config" not in str(e):
        raise e

##################
# 可在后台修改的一些设置
##################

try:
    from mainsys.config import *
except ImportError as e:
    if "config" not in str(e):
        raise e

##################
# 导入数据库配置
##################

try:
    from mainsys.dbconfig import *
except ImportError as e:
    if "dbconfig" not in str(e):
        raise e

####################
# DYNAMIC SETTINGS #
####################

try:
    from wenlincms.utils.conf import set_dynamic_settings
except ImportError:
    pass
else:
    set_dynamic_settings(globals())
